/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.dess.chat.utils;

import com.hyts.dess.chat.constant.NettyDataContainer;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Objects;

/**
 * @project-name:dess
 * @package-name:com.hyts.dess.chat.utils
 * @author:LiBo/Alex
 * @create-date:2020-07-28 20:33
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: Netty属性攻击类操作服务处理
 */
public class NettyAttrUtil {

    /**
     * 刷新心跳时间
     */
    public static void refreshLastHeartBeatTime(Channel channel){
        Objects.requireNonNull(channel,"校验channel为空!");
        channel.attr(NettyDataContainer.ATTR_KEY_LAST_HEARTBEAT_TIME).set(String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 获取最新一次的心跳时间
     * @param channel
     * @return
     */
    public static Long getLastHeartBeatTime(Channel channel){
        String value = getAttribute(channel, NettyDataContainer.ATTR_KEY_LAST_HEARTBEAT_TIME);
        if (StringUtils.isNotBlank(value) && NumberUtils.isNumber(value)) {
            return Long.valueOf(value);
        }
        return null;
    }

    /**
     * 获取userId信息操作
     * @param channel
     * @return
     */
    public static String getUserId(Channel channel) {
        String value = getAttribute(channel, NettyDataContainer.ATTR_KEY_USER_ID);
        return value;
    }


    /**
     * 设置用户id属性信息控制对象
     * @param channel
     * @param value
     */
    public static void setUserId(Channel channel, String value){
        Objects.requireNonNull(channel,"校验channel为空!");
        Objects.requireNonNull(value,"校验userId为空!");
        channel.attr(NettyDataContainer.ATTR_KEY_USER_ID).set(value);
    }

    /**
     * 操作的获取属性操作服务处对象
     * @param channel
     * @param key
     * @return
     */
    static String getAttribute(Channel channel, AttributeKey<String> key) {
        Objects.requireNonNull(channel,"校验channel为空!");
        Objects.requireNonNull(key,"校验key为空!");
        Attribute<String> attr = channel.attr(key);
        return attr.get();
    }
}
